package com.lw.leetcode.str.b;

/**
 * Created with IntelliJ IDEA.
 * str
 * 1286. 字母组合迭代器
 *
 * @author liw
 * @version 1.0
 * @date 2021/12/20 21:20
 */
public class CombinationIterator {

    public static void main(String[] args) {
        String str = "abc";
        int k = 2;
        CombinationIterator test = new CombinationIterator(str, k);

        System.out.println(test.next());
        System.out.println(test.hasNext());
        System.out.println(test.next());
        System.out.println(test.hasNext());
        System.out.println(test.next());
        System.out.println(test.hasNext());

    }


    private char[] chars;
    private int length;
    private int[] arr;
    private int j;
    private char[] items;
    private int combinationLength;
    private boolean flag = true;

    public CombinationIterator(String characters, int combinationLength) {
        this.chars = characters.toCharArray();
        this.length = characters.length();
        arr = new int[combinationLength];
        j = combinationLength - 1;
        this.combinationLength = combinationLength;
        items = new char[combinationLength];
        for (int i = 0; i < combinationLength; i++) {
            arr[i] = i;
            items[i] = chars[i];
        }
    }

    public String next() {
        for (int i = 0; i < combinationLength; i++) {
            items[i] = chars[arr[i]];
        }
        String str = String.valueOf(items);
        arr[j]++;
        while (arr[j] == j + length - combinationLength + 1) {
            j--;
            flag = j >= 0;
            if (flag) {
                arr[j]++;
            } else {
                break;
            }
        }
        j++;
        while (j < combinationLength) {
            if (flag) {
                arr[j] = arr[j - 1] + 1;
            }
            j++;
        }
        j--;
        return str;
    }

    public boolean hasNext() {
        return flag;
    }

}
